package com.sdp.refund.handle;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.refund.db.refund_apply.entity.RefundApply;
import com.sdp.refund.db.refund_apply.service.IRefundApplyService;
import com.sdp.refund.db.refund_user.entity.RefundUser;
import com.sdp.refund.db.refund_user.service.IRefundUserService;
import com.sdp.refund.utils.RefundConstants;

@Component
public class RefundApplyImpl extends RefundApplyHandle{
	
	@Autowired
	private IRefundUserService iRefundUserService;
	
	@Autowired
	private IRefundApplyService iRefundApplyService;

	@Override
	public BusinessContext execute(BusinessContext businessContext) {
		return ApplicationContextUtils.getBean(RefundApplyImpl.class).apply(businessContext);
	}
	
	@Transactional(rollbackFor=Exception.class)
	public BusinessContext apply(BusinessContext businessContext) {
		
		RefundApply refundApply = businessContext.get(RefundApply.class);
		List<String> refundStates = new ArrayList<>();
		refundStates.add(RefundConstants.退费状态_未申请.getCode());
		refundStates.add(RefundConstants.退费状态_申请驳回.getCode());
		
		List<RefundUser> userList = iRefundUserService.queryRefundUserByTelAndNameAndState(refundApply.getUserName(), refundApply.getUserTel(), refundStates);
		if(userList==null || userList.size()==0) {
			businessContext.setSuccess(false);
			businessContext.setMessage("您没有需要退费的信息，请先信息查询进行确认");
		}
		
		for(RefundUser user :userList) {
			user.setRefundState(RefundConstants.退费状态_已申请.getCode());
			user.setBankAc(refundApply.getBankAc());
			user.setBankNum(refundApply.getBankNum());
			user.setIdCardBackPhoto(refundApply.getIdCardBackPhoto());
			user.setIdCardFrontPhoto(refundApply.getIdCardFrontPhoto());
			user.setBankPhoto(refundApply.getBankPhoto());
			user.setIdNum(refundApply.getIdNum());
			user.setApplyTime(LocalDateTime.now());
		}
		refundApply.setApplyTime(LocalDateTime.now());
		iRefundApplyService.save(refundApply);
		iRefundUserService.updateBatchById(userList);
		return businessContext;
	}

}
